#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPWeb.
#    COOPWeb is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPWeb is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPWeb.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopweb/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopweb/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.db import models
#********************Setup psycopg2 and django section********************
from django.db import transaction
from django import db
import datetime, time
import os
import base64
from scapy.all import *
#grab latest from table1, parse, create table2 objects
#update table2 objects as needed





def ParseLogTAIPtoTableData():
    AVLSystemLog.ParseTAIP()
    AVLSystemLog.CalculatePoints()


def ImportPCap(Path):
    Files = os.listdir(Path)
    if len(Files) <= 1:
        return False
    OldestLog = min(Files) #files have suffix of unix timestamp; if this becomes in issue, use os.stat(path).st_mtime
    OldestReadIn = open(OldestLog, 'rb')
    PacketRaw = OldestReadIn.read()
    OldestReadIn.close()

    new = AVLSystemNetworkTraffic()
    new.CreateDateTime = datetime.datetime.now()
    PacketEncoded = base64.encodestring(PacketRaw)
    new.PacketCapture = PacketEncoded
    new.save()
    
    os.remove(OldestLog)
    return True

def ParseCapturedPCapToAVLSystemLogs():
    Logs = AVLSystemLog.objects.all()
    if not Logs.count():
        HighestParsedTrafficid = 0
    else:
        HighestParsedTrafficid = AVLSystemLog.objects.all().order_by('-AVLSystemNetworkTrafficid')[0].AVLSystemNetworkTrafficid
    UnparsedTraffic = AVLSystemNetworkTraffic.objects.filter(id__gt=HighestParsedTrafficid).order_by('id')
    for i in UnparsedTraffic:
        AVLSystemLog.CreateLogs(i)
        

WorkingDirectory = '/opt/coopweb/daemonlogger'
StartTime = datetime.datetime.now()
os.chdir(WorkingDirectory)
CurrentTime = datetime.datetime.now()
while (CurrentTime - StartTime).total_seconds() < 55:
    LogsFoundStatus = ImportPCap(WorkingDirectory)
    if not LogsFoundStatus:
        time.sleep(1)
        CurrentTime = datetime.datetime.now()
        continue
    ParseCapturedPCapToAVLSystemLogs()
    ParseLogTAIPtoTableData()
    CurrentTime = datetime.datetime.now()
db.close_connection()
sys.exit(0)

